﻿using Autodesk.Revit.DB;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Menu;
using xXYZ = Autodesk.Revit.DB.XYZ;
using TextBox = System.Windows.Forms.TextBox;

namespace RevitAddin
{
    public static class comMethod
    {
        /// <summary>
        /// 导入表格数据
        /// </summary>
        /// <param name="strFileName"></param>
        /// <returns></returns>
        public static List<CableContactItem> ReadCableContactItemExcel(string strFileName)
        {

            FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read, FileShare.None);
            StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));
            sr.ReadLine();
            List<CableContactItem> CCIList = new List<CableContactItem>();
            string str = "";
            while (str != null)
            {
                str = sr.ReadLine();

                if (!string.IsNullOrEmpty(str) && str.Contains(","))
                {
                    string[] xu = str.Split(',');
                    CableContactItem myjcw = new CableContactItem(xu[0], xu[1], xu[2], xu[3], xu[4], xu[5], xu[6]);

                    if (myjcw != null)
                    {
                        CCIList.Add(myjcw);
                    }
                }
            }
            sr.Close();


            return CCIList;
        }

        public static List<CableData> NewReadCableContactItemExcel(string strFileName)
        {

            FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read, FileShare.None);
            StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));
            sr.ReadLine();
            List<CableData> CCIList = new List<CableData>();
            string str = "";
            while (str != null)
            {
                str = sr.ReadLine();

                if (!string.IsNullOrEmpty(str) && str.Contains(","))
                {
                    string[] xu = str.Split(',');
                    CableData myjcw = new CableData(Convert.ToInt32(xu[0]), xu[1], xu[2], xu[3], Convert.ToBoolean(xu[4]), Convert.ToBoolean(xu[5]), Convert.ToBoolean(xu[6]));

                    if (myjcw != null)
                    {
                        CCIList.Add(myjcw);
                    }
                }
            }
            sr.Close();


            return CCIList;
        }


        public static string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
        public static string FileName = "";
        public static string xyzListToString(List<XYZ> xyzList)
        {
            string s = "";
            foreach (XYZ item in xyzList)
            {
                s += item.X.ToString() + "," + item.Y.ToString() + "," + item.Z.ToString() + ";";
            }
            return s;
        }
        /// <summary>
        /// 将Revit点转为自定义点
        /// </summary>
        /// <param name="xyzList"></param>
        /// <returns></returns>
        public static List<XYZ> xXYZ2XYZ(List<xXYZ> xyzList)
        {
            return xyzList.ConvertAll(e => new XYZ(e.X, e.Y, e.Z));
        }
        /// <summary>
        /// 保存配置数据
        /// </summary>
        /// <param name="path"></param>
        /// <param name="saveConfig"></param>
        /// <returns></returns>
        public static bool SaveConfig(string path, SaveConfig saveConfig)
        {

            bool temp = false;
            try
            {

                string msg = JsonConvert.SerializeObject(saveConfig);
                byte[] myByte = System.Text.Encoding.UTF8.GetBytes(msg);
                using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate))
                {
                    fsWrite.Write(myByte, 0, myByte.Length);
                    if (File.Exists(path))
                    {
                        temp = true;
                    }
                }
            }
            catch (Exception)
            {
                temp = false;
            }


            return temp;
        }

        public static bool NewSaveConfig(string path, NewSaveConfig saveConfig)
        {

            bool temp = false;
            try
            {

                string msg = JsonConvert.SerializeObject(saveConfig);
                byte[] myByte = System.Text.Encoding.UTF8.GetBytes(msg);
                using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate))
                {
                    fsWrite.Write(myByte, 0, myByte.Length);
                    if (File.Exists(path))
                    {
                        temp = true;
                    }
                }
            }
            catch (Exception)
            {
                temp = false;
            }


            return temp;
        }
        public static SaveConfig ReadConfig(string path)
        {
            SaveConfig ccp = null;
            try
            {
                if (!File.Exists(path))
                {
                    MessageBox.Show("文件" + path + "不存在", "温馨提示");
                    return null;
                }
                else
                {
                    using (FileStream fsRead = new FileStream(path, FileMode.Open))
                    {
                        int fsLen = (int)fsRead.Length;
                        byte[] heByte = new byte[fsLen];
                        int r = fsRead.Read(heByte, 0, heByte.Length);
                        string myStr = System.Text.Encoding.UTF8.GetString(heByte);
                        ccp = JsonConvert.DeserializeObject<SaveConfig>(myStr);
                        return ccp;
                    }
                }
            }
            catch (Exception)
            {
                return ccp;
            }
        }

        public static string ReadAPIPath()
        {
            string path = @"C:\ProgramData\Autodesk\Revit\Addins\2020\whdqh\api.ini";
            try
            {
                if (!File.Exists(path))
                {
                    File.Create(path);
                    return "";
                }
                else
                {
                    using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate))
                    {
                        int fsLen = (int)fsRead.Length;
                        byte[] heByte = new byte[fsLen];
                        int r = fsRead.Read(heByte, 0, heByte.Length);
                        string myStr = System.Text.Encoding.UTF8.GetString(heByte);

                        return myStr;
                    }
                }
            }
            catch (Exception)
            {
                return "";
            }
        }
        public static string ReadSkinPath()
        {
            string path = @"C:\ProgramData\Autodesk\Revit\Addins\2020\whdqh\skin.ini";
            try
            {
                if (!File.Exists(path))
                {
                    File.Create(path);
                    return "";
                }
                else
                {
                    using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate))
                    {
                        int fsLen = (int)fsRead.Length;
                        byte[] heByte = new byte[fsLen];
                        int r = fsRead.Read(heByte, 0, heByte.Length);
                        string myStr = System.Text.Encoding.UTF8.GetString(heByte);

                        return myStr;
                    }
                }
            }
            catch (Exception)
            {
                return "";
            }
        }
        public static bool SaveAPIPath(string url)
        {

            bool temp = false;
            try
            {

                string path = @"C:\ProgramData\Autodesk\Revit\Addins\2020\whdqh\api.ini";
                File.Delete(path);
                byte[] myByte = System.Text.Encoding.UTF8.GetBytes(url);
                using (FileStream fsWrite = new FileStream(path, FileMode.CreateNew))
                {
                    fsWrite.Write(myByte, 0, myByte.Length);
                    if (File.Exists(path))
                    {
                        temp = true;
                    }
                }
            }
            catch (Exception)
            {
                temp = false;
            }


            return temp;
        }
        /// <summary>
        /// 保留四位小数
        /// </summary>
        /// <param name="xyzList"></param>
        /// <returns></returns>
        public static List<XYZ> RoundXYZList(List<XYZ> xyzList)
        {
            int temp = 10000;
            return xyzList.ConvertAll(e => new XYZ(Math.Round(e.X * temp) / temp, Math.Round(e.Y * temp) / temp, Math.Round(e.Z * temp) / temp));
        }
        /// <summary>
        /// 保留四位小数
        /// </summary>
        /// <param name="xyz"></param>
        /// <returns></returns>
        public static XYZ RoundXYZ(XYZ xyz)
        {
            int temp = 10000;
            return new XYZ(Math.Round(xyz.X * temp) / temp, Math.Round(xyz.Y * temp) / temp, Math.Round(xyz.Z * temp) / temp);
        }

        /// <summary>
        /// 计算线缆长度
        /// </summary>
        /// <param name="resultDic"></param>
        /// <returns></returns>
        public static Dictionary<string, double> CalculateCableLengths(Dictionary<string, Dictionary<string, List<XYZ>>> resultDic)
        {
            var cableLengths = new Dictionary<string, double>();

            foreach (var device in resultDic)
            {
                string deviceNumber = device.Key; // 获取设备编号

                foreach (var cable in device.Value)
                {
                    string cableNumber = cable.Key; // 获取线缆编号
                    List<XYZ> xyzList = cable.Value; // 获取线缆的XYZ值列表

                    double totalLength = 0;
                    for (int i = 0; i < xyzList.Count - 1; i++)
                    {
                        XYZ point1 = xyzList[i];
                        XYZ point2 = xyzList[i + 1];

                        // 计算两点之间的距离
                        double distance = Math.Sqrt(
                            Math.Pow(point2.X - point1.X, 2) +
                            Math.Pow(point2.Y - point1.Y, 2) +
                            Math.Pow(point2.Z - point1.Z, 2)
                        );

                        totalLength += distance;
                    }

                    // 组合标识：设备编号-线缆编号
                    string identifier = $"{deviceNumber}-{cableNumber}";
                    cableLengths[identifier] = totalLength;
                }
            }

            return cableLengths;
        }

        /// <summary>
        /// 显示线缆长度到TextBox控件
        /// </summary>
        /// <param name="resultDic"></param>
        /// <param name="textBox"></param>
        public static void DisplayCableLengths(Dictionary<string, Dictionary<string, List<XYZ>>> resultDic, TextBox textBox)
        {
            var cableLengths = CalculateCableLengths(resultDic);

            // 拼接结果文本
            var resultText = new StringBuilder();
            foreach (var cable in cableLengths)
            {
                resultText.AppendLine($"{cable.Key}: {cable.Value:F2}"); // 保留两位小数
            }

            // 将结果显示到TextBox中
            textBox.Text = resultText.ToString();
        }
    }
}
